package easyProductConsumerDemo;



import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.log4j.Logger;


import java.util.Properties;



/**基于kafka_2.11-1.0.0
 * @program: KafkaSparkStreaming
 * @description
 * @author: tkk fendoukaoziji
 * @create: 2019-05-24 14:40
 **/
public class ProducerDemo {
    Logger logger = Logger.getLogger(ProducerDemo.class);
    public static final String brokerList="node2:9092,node3:9092,node4:9092";
    public static final String topic="topic-kafkaBook";
    public static void main(String[] args) {

        Properties properties = initConfig();
        //配置生产者客户端参数创建kafkaProducer实例        KafkaProducer是线程安全的，可以在多个线程共享单个KafkaProducer实例
        KafkaProducer<String,String> producer = new KafkaProducer<>(properties);
        //发送一条消息，未指定key  key=null,value="无语,Kafka!"
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, "第二次,Kafka!");
        try {
            producer.send(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        producer.close();

    }
    public static Properties initConfig(){
        Properties prop = new Properties();
        /*prop.put("bootstrap.servers",brokerList);
        prop.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        prop.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
        prop.put("client.id","producer.client.id.demo");*/
        //改进版本，使用ProducerConfig避免单词书写错误
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,brokerList);
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());//全限定名容易写错 所以可以改写为
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
        prop.put(ProducerConfig.CLIENT_ID_CONFIG,"producer.client.id.demo");

        return  prop;
    }
















}
